<template>
  <VPage v-loading="loading">
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <XForm
          :fieldList="fieldList"
          :formOption="optionsDataAll"
          :formData="form"
        >
          <template #warehouse="{ input, value }">
            <WarehouseSelect
              placeholder="请选择发货仓库"
              @update:model-value="input"
              :model-value="value"
              class="w-[200px]"
            />
          </template>
          <template #create_user="{ value, input }">
            <VCascader
              :model-value="value"
              @update:model-value="input"
              collapse-tags
              class="w-[200px]"
              placeholder="创建人"
            />
          </template>
        </XForm>
      </template>
      <template #toolbar_btns>
        <VActionBar :actions="actions">
          <template #right>
            <div class="ml-auto">
              <el-dropdown
                class="h-[28px]"
                @command="handleImport"
                v-hasPermi="[logisticsSettingsAuthList.channel.import]"
              >
                <el-button style="height: 28px">
                  导入<SvgIcon
                    icon-class="ArrowDown"
                    class="text-[12px] ml-[4px]"
                  />
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="1">起重续价</el-dropdown-item>
                    <el-dropdown-item command="2">区间续价</el-dropdown-item>
                    <el-dropdown-item command="3"
                      >头程重量计费</el-dropdown-item
                    >
                    <el-dropdown-item command="4"
                      >头程体积计费</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <el-dropdown
                class="ml-[12px] h-[28px]"
                @command="handleExport"
                v-hasPermi="[logisticsSettingsAuthList.channel.import]"
              >
                <el-button style="height: 28px">
                  导出<SvgIcon
                    icon-class="ArrowDown"
                    class="text-[12px] ml-[4px]"
                  />
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="export_ctc_qzxj"
                      >起重续价</el-dropdown-item
                    >
                    <el-dropdown-item command="export_ctc_qjxj"
                      >区间续价</el-dropdown-item
                    >
                    <el-dropdown-item command="export_ctc_tc_weight"
                      >头程重量计费</el-dropdown-item
                    >
                    <el-dropdown-item command="export_ctc_tc_volume"
                      >头程体积计费</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </VActionBar>
      </template>
      <template #channel_name="{ row }">
        <el-link type="primary" @click="handleEdit(row)">
          <!-- <router-link
            :to="`/logistics-settings/channel/add?id=${row?.id}`"
          ></router-link> -->
          {{ row?.channel_name }}
        </el-link>
      </template>
      <template #operation="{ row }">
        <el-button
          link
          type="primary"
          @click="handleEdit(row)"
          v-hasPermi="[logisticsSettingsAuthList.channel.edit]"
        >
          编辑
        </el-button>
        <el-button
          link
          :type="row.status === 0 ? 'primary' : 'danger'"
          @click="handleStatusRow(row)"
          v-hasPermi="[
            row.status === 0
              ? logisticsSettingsAuthList.channel.enable
              : logisticsSettingsAuthList.channel.disabled,
          ]"
        >
          {{ { 0: "启用", 1: "禁用" }[row.status] }}
        </el-button>
        <el-button
          link
          type="primary"
          @click="handleLog(row)"
          v-hasPermi="[logisticsSettingsAuthList.channel.log]"
        >
          日志
        </el-button>
      </template>
    </VTable>
    <Log
      dialog
      v-model="logVisible"
      :autoLoad="false"
      tag="channel.channel"
      :business_id="logId"
      @close="logId = ''"
    />
    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
    <import-dialog ref="importDialogRef" @refresh="refresh" />
  </VPage>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import Log from "@/components/Log/index.vue";
import XForm from "@/components/XForm/index.vue";
import WarehouseSelect from "@/components/WarehouseSelect/index.vue";
import { logisticsSettingsAuthList } from "@/Auth/logistics-settings.js";
import ImportDialog from "@/components/importDialogParams/index.vue";
import DerivedCenter from "@/components/DerivedCenter";
import { config_name } from "@/config/export.js";
import { overallOptions } from "@/api/public.js";
import { strHump } from "@/utils/index";
import { channelStatus, copyChannel, deleteChannel, channelList } from "./api";
import { statusMap } from "@/data";
import { getTableSelectRow, getTableSelect } from "@/hooks/tool.js";
import { getChannelList, logisticsList } from "@/api/index.js";
import SvgIcon from "@/components/SvgIcon/index.vue";
import action from "@/utils/action.js";
import { renderCustomSlot } from "@/hooks/renderTable.jsx";
const emits = defineEmits(["search"]);
const router = useRouter();
const { proxy } = getCurrentInstance();
const tableRef = ref();
const optionsData = ref({});
const tableOptins = reactive({
  formConfig: {
    data: {
      status: "",
      warehouse: "",
      dateRange: { type: "create_time", value: [], range: false }, // 组合+日期范围
      create_user: "",
      transport_type: "",
      is_registered: "",
      billing_type: "",
      collect_name: "",
      delivery_mode: "",
      logistics_id: "",
      channel_id: "",
    },
  },
  tooltipConfig: {
    showAll: false,
  },
  isToggle: true,
  columns: [
    { fixed: "left", width: 50, type: "checkbox" },
    { fixed: "left", width: 50, title: "编号", field: "id" },
    {
      fixed: "left",
      title: "渠道中文名称",
      width: 180,
      field: "channel_name",
      slots: { default: "channel_name" },
    },
    { title: "物流商", width: 120, field: "logistics_name" },
    {
      title: "运价文件",
      width: 160,
      slots: {
        default: ({ row }) => (
          <el-button text type="primary" onClick={() => handleLook(row)}>
            查看
          </el-button>
        ),
      },
    },

    { title: "计费类型", width: 120, field: "billing_type_text" },
    {
      title: "适用发货仓库",
      minWidth: 360,
      field: "warehouse",
      slots: renderCustomSlot("warehouse"),
    },
    { title: "是否挂号", width: 120, field: "is_registered_text" },
    { title: "运输类型", width: 200, field: "transport_type_text" },
    {
      title: "状态",
      width: 100,
      field: "status",
      slots: {
        default: ({ row }) => {
          return <VstatusRender code={row} />;
        },
      },
    },
    { title: "最近开始时间", width: 170, field: "start_time" },
    { title: "最近结束时间", width: 170, field: "end_time" },
    { title: "优选类型", width: 160, field: "delivery_mode_text" },
    { title: "揽收商", width: 210, field: "collect_name" },
    { title: "代理人", width: 160, field: "agent" },
    { title: "联系方式", width: 160, field: "contact" },
    { title: "更新人", width: 170, field: "update_user" },
    { title: "更新日期", width: 170, field: "update_time" },
    { title: "备注", width: 200, field: "remark" },
    {
      title: "操作",
      minWidth: 200,
      fixed: "right",
      slots: { default: "operation" },
    },
  ],
  proxyConfig: {
    autoLoad: false, // 是否自动加载查询数据
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: ({ page, form }) => {
        return channelList({ ...form, ...page }).then((res) => {
          return {
            data: res.data,
            total: res.total,
          };
        });
      },
    },
  },
});
const publicStyle = { style: { width: "240px" } };
const fieldList = [
  {
    field: "channel_id",
    type: "select",
    originOption: "channel",
    ...publicStyle,
    options: {
      placeholder: "渠道名称",
      labelKey: "channel_name",
      valueKey: "channel_id",
    },
    multiple: true,
    class: "select-wrapper-style",
  },
  {
    field: "status",
    placeholder: "状态",
    type: "select",
    options: {
      placeholder: "状态",
      data: statusMap,
    },
    style: { width: "90px" },
  },
  {
    field: "warehouse",
    slot: "warehouse",
  },
  {
    field: "dateRange",
    type: "dateTimeRange",
    style: { width: "360px" },
    itemProps: {
      startPlaceholder: "创建最早时间",
      endPlaceholder: "创建最晚时间",
    },
  },
  {
    field: "create_user",
    slot: "create_user",
  },
  {
    field: "transport_type",
    type: "select",
    options: {
      placeholder: "运输类型",
    },
    originOption: "transport_type",
  },
  {
    field: "is_registered",
    type: "select",
    options: {
      placeholder: "是否挂号",
    },
    originOption: "is_registered",
    style: { width: "120px" },
  },
  {
    field: "billing_type",
    type: "select",
    options: {
      placeholder: "计费类型",
    },
    originOption: "billing_type",
  },
  {
    field: "logistics_id",
    type: "select",
    options: {
      placeholder: "物流商",
      valueKey: "logistics_id",
      labelKey: "logistics_name",
    },
    originOption: "logistics",
  },
  {
    field: "collect_name",
    type: "input",
    placeholder: "揽收商",
  },
  {
    field: "delivery_mode",
    type: "select",
    options: {
      placeholder: "优选类型",
    },
    originOption: "delivery_mode",
  },
];

onMounted(() => {
  getOptions();
});

const getOptions = async () => {
  try {
    const params = "channel.channel";
    const { data } = await overallOptions({
      params: [params],
    });
    const _data = data?.[strHump(params)];
    if (_data) {
      optionsData.value = _data;
    }
  } catch (e) {
    console.error(e);
  }
};
const dict = reactive({});
//获取物流商
const getlogistics = () => {
  logisticsList({}).then((res) => {
    dict.logistics = res?.data || [];
  });
};
getlogistics();
const getChannel = async () => {
  const { data } = await getChannelList();
  dict.channel = data;
};
getChannel();
const optionsDataAll = computed(() => {
  return Object.assign({}, optionsData.value, dict);
});
const handleAdd = () => {
  action.setGlobalState({
    changeMicoTabsPath: {
      viewPath: "/tms/logistics-settings/channel/add",
      type: "closeTabByPath",
    },
  });
  router.push(`/logistics-settings/channel/add`);
};

const handleStatus = (status) => {
  const rows = getTableSelect(tableRef.value);
  if (!rows.length) return ElMessage.warning("请至少选择一条数据!");
  handleStatusReq(rows, status);
};
const handleStatusRow = (row) => {
  handleStatusReq([row.id], row.status ? 0 : 1);
};
const handleBatchDelete = async () => {
  const rows = getTableSelect(tableRef.value);
  if (!rows.length) return ElMessage.warning("请至少选择一条数据!");
  await handleDelete(rows);
};

const handleDelete = (id) => {
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认删除选中的
        <span class="text-[#3366F1] px-[4px]">{id.length || 1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          await deleteChannel({ id });
          ElMessage.success("操作成功");
          refresh();
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          getList();
        }
      } else {
        done();
      }
    },
  });
};
const loading = ref(false);
const handleCopy = async () => {
  const rows = getTableSelect(tableRef.value);
  if (!rows.length) return;
  if (rows.length > 1) {
    ElMessage.warning("复制渠道只能单个操作");
    return;
  }
  loading.value = true;
  try {
    const { code, message } = await copyChannel({ id: rows });
    if (code !== 200) {
      ElMessage.warning(message);
      return;
    }
    refresh();
  } catch (e) {
    console.error(e);
  } finally {
    loading.value = false;
  }
};

const handleStatusReq = (id, flag) => {
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认{flag ? "启用" : "禁用"}选中的
        <span class="text-[#3366F1] px-[4px]">{id.length || 1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          await channelStatus({ id, status: flag ? 1 : 0 });
          ElMessage.success("操作成功");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};

const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
//导出中心
const DerivedCenterRef = ref();
const handleExport = (command) => {
  let con = config_name["logistics_settings"][command];
  let condition = getTableSelectRow(tableRef.value);
  DerivedCenterRef.value?.open({
    tag_name: con,
    condition,
  });
};
const handleLook = (row) => {
  router.push({
    path: `/logistics-settings/channel/transport-cost`,
    query: { id: row.id, currency: row?.currency || "CNY" },
  });
};

const handleEdit = (item) => {
  action.setGlobalState({
    changeMicoTabsPath: {
      viewPath: "/tms/logistics-settings/channel/add",
      type: "closeTabByPath",
    },
  });
  router.push({
    path: `/logistics-settings/channel/add`,
    query: { id: item.id },
  });
};

const logId = ref("");
const logVisible = ref(false);
const handleLog = (item) => {
  logId.value = item.id;
  logVisible.value = true;
};

//导入
const importDialogRef = ref();
const handleImport = (command) => {
  let obj = {
    1: {
      type: "channel.ctc.1",
      urlType: "/v2/business-import/channel-transport-cost",
    },
    2: {
      type: "channel.ctc.2",
      urlType: "/v2/business-import/channel-transport-cost",
    },
    3: {
      type: "channel.ctc.3",
      urlType: "/v2/business-import/channel-transport-cost",
    },
    4: {
      type: "channel.ctc.4",
      urlType: "/v2/business-import/channel-transport-cost",
    },
  };
  importDialogRef.value?.open({
    type: obj[command]["type"],
    urlType: obj[command]["urlType"],
    business_params: { billing_type: command },
  });
};
const actions = [
  {
    label: "新增",
    icon: "add2",
    type: "primary",
    fn: handleAdd,
    permission: [logisticsSettingsAuthList.channel.add],
  },
  {
    label: "启用",
    icon: "state_finish_line_1",
    type: "primary",
    fn: () => handleStatus(true),
    permission: [logisticsSettingsAuthList.channel.enable],
  },
  {
    label: "禁用",
    icon: "state_disabled",
    fn: () => handleStatus(false),
    permission: [logisticsSettingsAuthList.channel.disabled],
  },
  {
    label: "复制",
    icon: "copy",
    fn: handleCopy,
    permission: [logisticsSettingsAuthList.channel.copy],
  },

  {
    label: "删除",
    icon: "del",
    fn: handleBatchDelete,
    permission: [logisticsSettingsAuthList.channel.delete],
  },
  // {
  //   label: "导入头程渠道附加费",
  //   right: true,
  //   icon: "download1",
  //   fn: handleImport,
  // },
  // {
  //   label: "导出",
  //   right: true,
  //   icon: "import",
  //   fn: handleExport,
  //   permission: [logisticsSettingsAuthList.channel.export],
  // },
];
</script>
